﻿using Sub.TaskPlanningDesk.Model.Objects;
using Sub.TaskPlanningDesk.Model.Repositories;
using System.Linq;
using System;

namespace Sub.TaskPlanningDesk.Model.Services.Projects
{
	public class TaskService : ITaskService
	{
		#region ctor

		private ITaskRepository _taskRepository;

		public TaskService(ITaskRepository taskRepository)
		{
			_taskRepository = taskRepository;
		}

		#endregion

		public Task[] GetTasks(int projectID, bool showUnCompleted)
		{
			var tasks = _taskRepository.GetTasksByProjectID(projectID);
			if (!showUnCompleted)
				return tasks.Where(r => !r.IsDone).ToArray();
			return tasks;
		}

		public void Create(Task task)
		{
			task.Created = DateTime.Now.ToUniversalTime();
			_taskRepository.Create(task);
		}

		public void Update(Task task)
		{
			_taskRepository.Update(task);
		}

		public void Delete(int taskID)
		{
			_taskRepository.Delete(taskID);
		}

		public Task ByID(int taskID)
		{
			return _taskRepository.ByID(taskID);
		}

		public void ChangeOrder(int projectID, string newIDs)
		{
			var tasks = _taskRepository.GetTasksByProjectID(projectID);
			string[] listOfIDs = newIDs.Split('-');

			int orderStart = 1;
			foreach (var item in listOfIDs)
			{
				int id = Int32.Parse(item);
				var task = tasks.Single(r => r.ID == id);
				task.Order = orderStart++;
			}

			foreach (var item in tasks)
			{
				_taskRepository.Update(item);
			}
		}

		public void Done(int taskID)
		{
			SetDoneStatus(taskID, true);
		}

		public void UnDone(int taskID)
		{
			SetDoneStatus(taskID, false);
		}

		private void SetDoneStatus(int taskID, bool status)
		{
			var task = _taskRepository.ByID(taskID);
			task.IsDone = status;
			_taskRepository.Update(task);
		}

		
	}
}
